#include "LakeEdit.h"

#include "GL\glew.h"
#include "GL\freeglut.h"
#ifdef _DEBUG
#include <iostream>
#endif

LakeEdit::LakeEdit()
{
  lakeStarted = false;
}

void LakeEdit::setPoint(float pos[3])
{
  if(!lakeStarted)
  {
    lakeStarted = true;
    memcpy(startpos,pos,sizeof(float)*3);
  }
  else
  {
    lakeStarted = false;
    pos[1] = startpos[1]; // same height
    memcpy(endpos,pos,sizeof(float)*3);
    makeLake();
  }
}

void LakeEdit::makeLake()
{
  int w = int( endpos[0] - startpos[0] );
  int h = int( endpos[2] - startpos[2] );
  w = abs(w);
  h = abs(h);

	// Not possible to make smaller lakes than 10x10 meters
	if( w < 10 || h < 10)
	{
		#ifdef _DEBUG
		std::cout << "Error: Lake area too small" << std::endl;
		#endif
	}
	else
	{
		Rect2D r;
		memcpy(r.startpos,startpos,sizeof(float)*3);
		memcpy(r.endpos,endpos,sizeof(float)*3);
		lakeRects.push_back( r );

		Plane p(w,h);
		p.init();
		lakePlanes.push_back( p );
	}
}

void LakeEdit::render(double time)
{
  glColor3f(1,0,0);
  for(size_t i=0; i<lakeRects.size(); i++)
  {
    glPushMatrix();
    glTranslatef( lakeRects[i].startpos[0], lakeRects[i].startpos[1], lakeRects[i].startpos[2] );
    glutWireSphere(1,12,12);
    glPopMatrix();
    glPushMatrix();
    glTranslatef( lakeRects[i].endpos[0], lakeRects[i].endpos[1], lakeRects[i].endpos[2] );
    glutWireSphere(1,12,12);
    glPopMatrix();
  }

  for(size_t i=0; i<lakePlanes.size(); i++)
  {
    glPushMatrix();
    float w = lakeRects[i].endpos[0] - lakeRects[i].startpos[0];
    float h = lakeRects[i].endpos[2] - lakeRects[i].startpos[2];

    float x = lakeRects[i].startpos[0] + w/2;
    float y = lakeRects[i].startpos[1];
    float z = lakeRects[i].startpos[2] + h/2;

    glTranslatef(x,y,z);
    lakePlanes[i].render(time);
    glPopMatrix();
  }
}

